package com.jchy.photo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

/**
 * 
 * @author chyjm
 */
public class FileUtil {

	/**
	 * 
	 * @param start
	 * @param offset
	 * @return String[]
	 * 
	 *         RecursiveList works like File.list except it recursively
	 *         traverses subdirectories removing those subdirectories from the
	 *         resulting list.
	 * 
	 *         start should not have a trailing separator and offset should have
	 *         neither a leading nor a trailing separator.
	 * 
	 */
	public static String[] recursiveList(String start, String offset) {

		String[] items, currSubItems, result;
		ArrayList<String> allSubItems, subDirs, resultArrayList;
		File item, fileDirectory;
		String nextOffset;

		currSubItems = new String[0];
		allSubItems = new ArrayList<String>();
		subDirs = new ArrayList<String>();
		if (offset.equals(""))
			fileDirectory = new File(start);
		else
			fileDirectory = new File(start + File.separator + offset);

		if (fileDirectory.isDirectory()) {

			items = fileDirectory.list();

			for (int i = 0; i < items.length; i++) {
				if (offset.equals(""))
					nextOffset = items[i];
				else
					nextOffset = offset + File.separator + items[i];
				item = new File(start + File.separator + nextOffset);
				if (item.isDirectory()) {
					currSubItems = recursiveList(start, nextOffset);
					for (int j = 0; j < currSubItems.length; j++)
						allSubItems.add(currSubItems[j]);
					subDirs.add(items[i]);
				}
			}

			resultArrayList = new ArrayList<String>();
			for (int i = 0; i < items.length; i++) {
				if (!subDirs.contains(items[i])) {
					if (offset.equals(""))
						resultArrayList.add(items[i]);
					else
						resultArrayList.add(offset + File.separator + items[i]);
				}
			}
			resultArrayList.addAll(allSubItems);

			result = new String[resultArrayList.size()];
			result = resultArrayList.toArray(result);
		} else
			result = null;

		return result;

	}

	/**
	 * 
	 * @param Source File File
	 * @param Destination File
	 * @return Boolean - whether the file was copied or not
	 */
	public static boolean copyfile(String srFile, String dtFile) {

		boolean result = true;

		try {
			File f1 = new File(srFile);
			File f2 = new File(dtFile);
			InputStream in = new FileInputStream(f1);

			OutputStream out = new FileOutputStream(f2);

			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
		} catch (FileNotFoundException ex) {
			result = false;
		} catch (IOException e) {
			result = false;
		}

		return result;
	}
}
